package com.cjh.utils;

import com.cjh.constant.JwtConstant;
import io.jsonwebtoken.*;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * jwt工具类
 */
@Component
public class JwtUtils {

    /**
     * 生成token
     * @param userId
     * @return
     */
    public static String createToken(String userId){

        JwtBuilder jwtBuilder = Jwts.builder();
        String token = jwtBuilder
                //header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //payload
                .claim("username", "cjh")
                .setSubject(userId)
                .setExpiration(new Date(System.currentTimeMillis() + JwtConstant.EXPIRE_TIME*1000))
                .setId(UUID.randomUUID().toString().replace("-", ""))
                //signature
                .signWith(SignatureAlgorithm.HS256, JwtConstant.SIGN)
                .compact();

        return token;
    }

    /**
     * 解析token
     * main方法调用时HttpServletResponse参数需传入null
     * @param response
     * @param token
     * @return
     */
    public static String parseToken(HttpServletResponse response,String token){

        String subject = null;
        if (Objects.equals(token.trim(),"")){
            ResponseUtil.returnJson(response,ResultJson.fail(400,"Authorization参数值为空"));
            return null;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(JwtConstant.SIGN).parseClaimsJws(token);
            subject = claimsJws.getBody().getSubject();
        } catch (ExpiredJwtException e) {
            if (Objects.isNull(response)) {
                throw new RuntimeException("token参数过期");
            }
            ResponseUtil.returnJson(response,ResultJson.fail(401,"认证失效,请重新登录"));
        } catch (MalformedJwtException e) {
            if (Objects.isNull(response)) {
                throw new RuntimeException("token参数不合法");
            }
            ResponseUtil.returnJson(response,ResultJson.fail(400,"Authorization参数不合法"));
        } catch (SignatureException e) {
            if (Objects.isNull(response)) {
                throw new RuntimeException("签名不合法");
            }
            ResponseUtil.returnJson(response,ResultJson.fail(400,"签名不合法"));
        }
        return subject;

    }

    public static void main(String[] args) {
        String token = JwtUtils.createToken("1");
        System.out.println(token);
        System.out.println(JwtUtils.parseToken(null,token));
    }
}
